﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sharp.DataTransferObject;
using Sharp.Domain.Model;
using Sharp.Domain.PlatformBoundedContext.MessageModule.Aggregates;
using Sharp.Infrastructure;
using Sharp.Infrastructure.Crosscutting;
using Sharp.Infrastructure.Search;

namespace Sharp.Application.Platform
{
    public partial class UserServiceImpl
    {
        #region 消息

        [Logging("发送消息“{@p0.Title}”")]
        public Result SendMessage(MessageDTO model)
        {
            Result res = new Result();

            if (model.Id.IsEmpty())
            {
                var info = model.To<Message>();
                info.PublishTime = DateTime.Now;
                info.SenderId = ContactContext.Current.UserId;
                info.Sender = _userRepository.Get(info.SenderId.Value);

                if (!model.RecipientName.IsNullOrEmpty())
                {
                    var user = _userRepository.Get(x => x.UserName == model.RecipientName.Trim());
                    if (user != null)
                    {
                        info.ReceiverId = user.Id;
                    }
                }
                if (info.ReceiverId.IsEmpty())
                {
                    info.EntityState = EntityStateOperate.IsDraft;
                }

                _messageRepository.Add(info);
            }
            else //从草稿转为正式和修改草稿都走这里
            {
                var info = _messageRepository.Get(model.Id);
                info.Content = model.Content;
                if (!model.RecipientName.IsNullOrEmpty())
                {
                    var user = _userRepository.Get(x => x.UserName == model.RecipientName.Trim());
                    if (user != null)
                    {
                        info.ReceiverId = user.Id;
                    }
                }
                if (info.ReceiverId.IsEmpty())
                {
                    info.EntityState = EntityStateOperate.IsDraft;
                }
                else
                {
                    info.EntityState = EntityStateOperate.Normal;
                }
            }

            Context.Commit();
            return res;
        }

        [Logging("消息存为草稿“{@p0.Title}”")]
        public Result DraftMessage(MessageDTO model)
        {
            Result res = new Result();
            var info = model.To<Message>();

            info.PublishTime = DateTime.Now;
            info.SenderId = ContactContext.Current.UserId;
            info.Sender = _userRepository.Get(info.SenderId.Value);
            info.Content = model.Content;
            if (!model.RecipientName.IsNullOrEmpty())
            {
                var user = _userRepository.Get(x => x.UserName == model.RecipientName.Trim());
                if (user != null)
                {
                    info.ReceiverId = user.Id;
                }
            }
            info.EntityState = EntityStateOperate.IsDraft;

            _messageRepository.Add(info);

            Context.Commit();
            return res;
        }

        [Logging("删除消息“{@p0}”")]
        public Result DeleteMessages(Guid[] ids)
        {
            var res = new Result();
            if (ids == null)
            {
                res.Err = "Id参数不可为空！";
                return res;
            }

            _messageRepository.Remove(ids);
            Context.Commit();
            return res;
        }

        public MessageDTO GetMessageInfo(Guid id)
        {
            return _messageRepository.Get(id).To<MessageDTO>();
        }

        /// <summary>
        /// 未读消息
        /// </summary>
        /// <returns></returns> 
        public Result<IList<MessageDTO>> NoReadMessages()
        {
            var list = _messageRepository.GetList(x => !x.IsReaded && x.ReceiverId == ContactContext.Current.UserId,
                10, x => x.Sender.Profile).To<List<MessageDTO>>();

            return new Result<IList<MessageDTO>>()
            {
                Data = list
            };
        }

        public PagedResult<MessageDTO> GetMessagePaged(PagingFeature pf)
        {
            var paged = _messageRepository.Pagging(pf, x => x.ReceiverId == ContactContext.Current.UserId);

            var output = paged.To<Message, MessageDTO>();
            output.Data.ForEach(x =>
            {
                x.SenderName = _userRepository.SelectFirst(u => u.Id == x.SenderId, y => y.UserName, null);
            });

            return output;
        }
        public PagedResult<MessageDTO> GetMessageOutboxPaged(PagingFeature pf)
        {
            var paged = _messageRepository.GetOutboxPagging(pf, ContactContext.Current.UserId);

            var output = paged.To<Message, MessageDTO>();
            output.Data.ForEach(x =>
            {
                x.SenderName = _userRepository.SelectFirst(u => u.Id == x.SenderId, y => y.UserName, null);
            });

            return output;
        }
        public PagedResult<MessageDTO> GetMessageDraftboxPaged(PagingFeature pf)
        {
            var paged = _messageRepository.GetDraftboxPagging(pf, ContactContext.Current.UserId);

            var output = paged.To<Message, MessageDTO>();
            output.Data.ForEach(x =>
            {
                x.SenderName = _userRepository.SelectFirst(u => u.Id == x.SenderId, y => y.UserName, null);
            });

            return output;
        }
        public PagedResult<MessageDTO> GetMessageDustbinPaged(PagingFeature pf)
        {
            var paged = _messageRepository.GetDustbinPagging(pf, ContactContext.Current.UserId);

            var output = paged.To<Message, MessageDTO>();
            output.Data.ForEach(x =>
            {
                x.SenderName = _userRepository.SelectFirst(u => u.Id == x.SenderId, y => y.UserName, null);
            });

            return output;
        }
        #endregion
    }
}
